import jsonpath
from requests import Response

from utils.util_logger import logger
from utils.util_yaml_file import YamlUtil
from utils.util_sql_action import DBUtil


class UtilExtractData:

    @classmethod
    def save_response_data(cls, response: Response, extract_data: dict, db_class: DBUtil=None):
        """
            提取响应数据:
            response: 接口响应原始数据
            extract_data: 需要提取的数据字典, 如：{'access_token': '$.data.token'}

        """
        json_response = response.json()
        try:
            for k, v in extract_data.items():
                actul_extract = jsonpath.jsonpath(json_response, v)[0]
                if not db_class:
                    YamlUtil.write_yaml("/test_manager/extract_data.yaml", data={k: actul_extract})
                else:
                    setattr(db_class, k, actul_extract) 
                logger.info(f"提取字段{k}成功: {actul_extract}")
                
        except Exception as e:
            logger.error(f"提取字段{k}异常!")